import Vue from 'vue';
import Router from 'vue-router';
import NavConfig from './nav.config.json';
// function getVue(path) {
//   return require('../pages'+path, resolve);
// }

const registerRoute = (config) => {
  let routes = [],
    firstLevelField = '',
    secoundLevelField = '';
  config.map(nav =>
    nav.list.map((page) =>{
        firstLevelField = {
          name: page.name,
          path: page.path,
          component: () => import('../pages' + page.filePath),
          meta: {
            title: page.title
          },
          children: []
        };
        let n = page.children.length;
        if(n === 0) {
          false;
        }
        if(n > 0) {
          secoundLevelField = '';
          page.children.map((child) => {
            secoundLevelField = {
              name: child.name,
              path: child.path,
              component: () => import('../pages' + child.filePath),
              meta: {
                title: child.title
              }
            };
            firstLevelField.children.push(secoundLevelField);
          })
        }

        routes.push(firstLevelField);
      }
    )
  );
  return { routes, navs: config }
};

const route = registerRoute(NavConfig);

route.routes.push({
  path: '*',
  redirect: '/index'
});

Vue.use(Router);
Vue.prototype.$setgoindex = function () {
  if (window.history.length <= 1) {
    if (location.href.indexOf('?') === -1) {
      window.location.href = location.href + '?goindex=true'
    } else if (location.href.indexOf('?') !== -1 && location.href.indexOf('goindex') === -1) {
      window.location.href = location.href + '&goindex=true'
    }
  }
};

export default  new Router({
  mode: 'history',
  base: __dirname,
  scrollBehavior () {
    return { x: 0, y: 0 }
  },
  routes:route.routes
});
